﻿using INTEX.DataBase;
using ReflectionStudio.Components.UserControls;
using ReflectionStudio.Core;
using ReflectionStudio.Core.Events;
using ReflectionStudio.Core.Helpers;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OracleClient;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using WPFExcelReport.Helpers;
using ReflectionStudio.Controls;
namespace WPFExcelReport
{
    /// <summary>
    /// Interaction logic for ProductionOrder.xaml
    /// </summary>
    public partial class YCAFSAV95 : DocumentBase
    {
        #region-------------Properties-----------------------
        bool IsLoaded = false;
        DataRow LastRow = null;
        DataSet SetMap = null;
        public OracleConnection OracleDB;
        public OracleCommand orlReadCommand = new OracleCommand();
        public IntexReptServBLClient proxy;
        private Dictionary<string, object> dicParamater;
        public DataSet dsResult;
        YCAFSAV95Data m_Data, m_DataX;
        public DataSet dsParamaters;
        YCAFSAV95Report m_rpt;
        DataTable tbUser = null;
        GB2312Convert8859P1 gb2312=new GB2312Convert8859P1();
        public SETINTEXDB SetEnv
        {
            get
            {
                return (SETINTEXDB)TryFindResource("SetEnv");
            }
        }
        public SETINTEXDB SetData
        {
            get
            {
                return (SETINTEXDB)TryFindResource("SetData");
            }
        }
        public SETINTEXDB SetProd
        {
            get
            {
                return (SETINTEXDB)TryFindResource("SetProd");
            }
        }
        CollectionViewSource vwABPOS_MAT
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwABPOS_MAT");
            }
        }
        CollectionViewSource vwEKPOS
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwEKPOS");
            }
        }
        CollectionViewSource vwABPOS
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwABPOS");
            }
        }
        DataRow dwABPOS
        {
            get
            {
                if (vwABPOS.View == null)
                    return null;
                if ((DataRowView)vwABPOS.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwABPOS.View.CurrentItem).Row;
            }
        }
        CollectionViewSource vwLIEFDAT
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwLIEFDAT");
            }
        }
        DataRow dwLIEFDAT
        {
            get
            {
                if (vwLIEFDAT.View == null)
                    return null;
                if ((DataRowView)vwLIEFDAT.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwLIEFDAT.View.CurrentItem).Row;
            }
        }
        
        CollectionViewSource vwPABPOS
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwPABPOS");
            }
        }
        DataRow dwPABPOS
        {
            get
            {
                if (vwPABPOS.View == null)
                    return null;
                if ((DataRowView)vwPABPOS.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwPABPOS.View.CurrentItem).Row;
            }
        } 

        string ART
        {
            get
            {
                return m_Data.Left(txtFSART.Text.ToString() + "                      ", 20);
            }
        }
        BindingListCollectionView cvABPOS
        {
            get
            {
                return (BindingListCollectionView)CollectionViewSource.GetDefaultView(dlgABPOS.ItemsSource);
            }
        }
        string TOLINES
        { 
            get
            {
                if (txtLAffectedLines.Text.ToString().Trim() == "")
                {
                    return txtLExistingLines.Text.ToString();
                }
                return txtLAffectedLines.Text.ToString();
            }
            set
            {
                txtLAffectedLines.Text = value;
            }
        }
        string Year
        {
            get
            {
                if (txtYear.Text .Trim() == "")
                {
                    MessageBox.Show("请设定年限");
                }
                return Helpers.Helper.Left(txtYear.Text.ToString() + "    ", 5);
            }
            set
            {
                txtYear.Text = value;
            }
        }
        string user = "";
        #endregion
        public YCAFSAV95()
        {
            InitializeComponent();
            this.Name = "生产跟踪";
        }
        public override void SetUp(Dictionary<string, object> dicParamater)
        {
            dicParamater["blBuildCellMastrix"] = false;
            base.SetUp(dicParamater);
            InitializeComponent();
            this.dicParamater = dicParamater;
            OracleDB = (OracleConnection)dicParamater["OracleDB"];
            proxy = (IntexReptServBLClient)dicParamater["proxy"];
            tbUser = (DataTable)dicParamater["USERRIGHT"];
            m_Data = new YCAFSAV95Data(OracleDB, proxy);
            user = (string)dicParamater["User"];
            txtFSART.Text = "2";
            txtPhoto.Text = "R:";
            ReSetEnv();
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                if (IsLoaded)
                    return;
                IsLoaded = true;
                vwABPOS.View.CurrentChanged += vwABPOS_CurrentChanged;
                DataRow dwData = SetData.FSSTAMM.NewRow();
                dwData["FSMANDANT"] = "00";
                DataSet SResult=m_Data.INTEXDBC.QueryFSSTAMM(dwData, 7);
                foreach (DataRow row in SResult.Tables[0].Rows)
                {
                    txtYear.Text = row["FSKOLL"].ToString();
                }                 
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return;
        }      
        public void ReSetEnv()
        {
            SetMap = new DataSet();
            DataSet setResult = new DataSet();
            /*string filePath = Path.Combine(PathHelper.ApplicationPath, "Report\\Interface\\FSCOMAPINTEX.XML");
            setResult.ReadXml(filePath);
            SetMap.Merge(setResult);
            m_Data.SetCAD = SetMap;
            m_Data.SetExt = new DataSet();*/
            try
            {
                setResult = m_Data.LoadEnv();
                SetEnv.Clear();
                SetEnv.Merge(setResult);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            finally
            {
                SetEnv.Clear();
                SetEnv.Merge(setResult);
            }
        } 

        void vwABPOS_CurrentChanged(object sender, EventArgs e)
        {
            if (dwABPOS == null)
                return;
            if (LastRow == dwABPOS)
                return;
            LastRow = dwABPOS;
            DataSet SResult = new DataSet();
            try
            {
                //cvABPOS.CustomFilter = null;
                txtFSART.Text = dwABPOS["ABPART"].ToString();
                using (new LongOperation(this, "数据更新中"))
                {
                    SResult = m_Data.BuildData(SetData, dwABPOS);
                    SetProd.Clear();
                    SetProd.Merge(SResult);
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            finally
            {
                if (SResult.Tables.Count > 0)
                {
                    btnRefreshPlanData_Click(null, null);
                    /*
                    DataRow[] rows;
                    foreach (DataRow vw in SetProd.ICC_ABPOS_MCO.Rows)
                    {
                        string KRS = vw["KRS"].ToString();
                        string LFD = vw["LFD"].ToString();
                        string ART = vw["ART"].ToString();
                        string VAR = vw["VAR"].ToString();
                        rows = SetData.ICC_ABPOS_MCO.Select("ART = '" + ART + "' AND VAR='" + VAR + "' AND KRS='" + KRS + "' AND LFD='" + LFD + "'");
                        foreach (DataRow rw in rows)
                        {
                            rw.Delete();
                        }
                    }
                    SetData.AcceptChanges();*/
                    if (vwPABPOS.View != null)
                    {
                        vwPABPOS.View.MoveCurrentToFirst();
                    }

                }
                txtLExistingLines.Text = "";
                txtLAffectedLines.Text = "";
                string lines = "";
                foreach (DataRow rx in SetProd.ABPOS.Rows)
                {
                    lines +=rx["ABPAUFPOS"].ToString() + ";";
                }
                //lines = (lines + "***").Replace(",***", "");
                txtLExistingLines.Text = lines;
                txtLAffectedLines.Text = lines;
            }
        }
        private void RefreshSetData(DataRow dwInput)
        {

            DataRow[] rows;
            string KRS = dwInput["KRS"].ToString();
            string LFD = dwInput["LFD"].ToString();
            rows = SetData.ICC_ABPOS_MAT.Select("KRS='" + KRS + "' AND LFD='" + LFD + "'");
            foreach (DataRow rw in rows)
            {
                var query = (from rx in SetProd.ICC_ABPOS_MAT.AsEnumerable()
                            where rx["ABID"].ToString() == rw["ABID"].ToString() 
                            select rx).First();
                rw.ItemArray = query.ItemArray;
            }
         
        }
        private void btnRefreshPlanData_Click(object sender, EventArgs e)
        {
            DataSet SResult = new DataSet();
            try
            {
                using (new LongOperation(this, "数据更新中"))
                {
                    SetProd.Merge(SetEnv.SDDAT);
                    SResult = m_Data.ResetData(SetProd, dwABPOS, txtPhoto.Text.ToString().Trim());
                    SetProd.Clear();
                    SetProd.Merge(SResult);
                    RefreshSetData(dwABPOS);

                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            finally 
            {

            }
        }
        private void btnRefresh_Click(object sender, EventArgs e)
        {
            DataSet SResult = new DataSet();
            try
            {//FSMANDANT	FSART	FSVAR
                DataRow dwInput = null;
                using (new LongOperation(this, "数据更新中"))
                {
                    dwInput = SetProd.ICC_ABPOS_MAT.NewRow();
                    dwInput["ABEND"] = "NO ";
                    dwInput["ABPART"] = ART;
                    dwInput["KOLL"] = Year;
                    SResult = m_Data.Refresh(dwInput,txtSection.Text);
                    SetData.Clear();
                    SetData.Merge(SResult);
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            finally
            {
                if (vwABPOS.View != null)
                {
                    vwABPOS.View.MoveCurrentTo(-1);
                }
            }
        }
        private void btnPrint_Click(object sender, EventArgs e)
        {

            DataSet setRpt = new DataSet();

            if (setRpt == null)
                return;
            m_DataX = new YCAFSAV95Data(dicParamater);
            m_DataX.OracleDB = this.OracleDB;
            m_DataX.proxy = this.proxy;
            if (m_DataX.exAgent._app == null)
            {
                m_DataX.exAgent = new ExcelX.ExcelLib.ExcelAgent(dicParamater);
            }
            m_rpt = new YCAFSAV95Report(dicParamater);
            m_rpt.dsSource = SetData;
            m_rpt.exAgent = m_DataX.exAgent;
            m_rpt.WriteExcelReport("OpenExcel");
        }
        private void btnSame_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (dwPABPOS == null)
                    return;
                foreach (DataRow rx in SetProd.ICC_ABPOS_MAT.Rows)
                {
                    if (rx["ABEND"].ToString().Trim() != "DEL")
                    {
                        rx["ABEND"] = "NO ";
                    }
                    m_Data.INTEXDBC.UpdateICC_ABPOS_MAT(rx);
                }

            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (dwPABPOS == null)
                    return;
                foreach (DataRow rx in SetProd.ICC_ABPOS_MAT.Rows)
                {
                    if (rx["ABEND"].ToString().Trim() != "DEL")
                    {
                        rx["ABEND"] = "NO ";
                    }
                    m_Data.INTEXDBC.UpdateICC_ABPOS_MAT(rx);
                }
                RefreshSetData(dwPABPOS);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        private void btnRelease_Click(object sender, RoutedEventArgs e)
        {
            try
            {

                if (dwPABPOS == null)
                    return;
                string status = dwPABPOS["ABPSPGRD"].ToString();
                if (status.Trim() == "")
                    status = "0";
                if (System.Convert.ToInt32(status)>89)
                { 
                    MessageBox.Show("主面料尚未批复");
                }
                string pos = "";
                foreach (DataRow row in SetProd.ABPOS.Rows)
                {
                    pos = row["ABPAUFPOS"].ToString() + ";";
                    if (!TOLINES.Contains(pos))
                        continue;
                    row["ABPSPGRD"] = "  ";
                    row["ABPGESSTA"] = "TE";
                    m_Data.INTEXDBC.SaveABPOS(row);
                }
                foreach (DataRow row in SetProd.ICC_ABPOS_MAT.Rows)
                {
                    row["ABPSPGRD"] = "  ";
                    row["ABPGESSTA"] = "TE";
                    m_Data.INTEXDBC.UpdateICC_ABPOS_MAT(row);
                }
                RefreshSetData(dwPABPOS);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex); 
            }
        }
        private void btnApprove_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (dwPABPOS == null)
                    return;
                foreach (DataRow rx in SetProd.ICC_ABPOS_MAT.Rows)
                {
                    if (rx["ABEND"].ToString().Trim() != "DEL")
                    {
                        rx["ABEND"] = "YES ";
                    }
                    m_Data.INTEXDBC.SaveICC_ABPOS_MCO(rx);
                }
                RefreshSetData(dwPABPOS);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }

        private void btnDelProd_Click(object sender, RoutedEventArgs e)
        {
            if (dwPABPOS == null)
                return;
            string filter = "KRS='" + dwPABPOS["KRS"].ToString() + "' AND LFD ='" + dwPABPOS["LFD"].ToString() + "' ";
            DataRow[] rows = SetProd.ICC_ABPOS_MAT.Select(filter);
            foreach (DataRow row in rows)
            {
                row["ABEND"] = "DEL";
                m_Data.INTEXDBC.UpdateICC_ABPOS_MAT(row);
            }
            RefreshSetData(dwPABPOS);
        }
        private void btnFilter_Click(object sender, RoutedEventArgs e)
        {
            string sections = Helpers.Helper.ParseSectionStr(txtSection.Text);
            string filter = "ABPART LIKE '%" + txtFSART.Text.ToString().Trim() + "%' AND SECTION IN (" + sections + ")";
            cvABPOS.CustomFilter = filter;
        }
        private void btnFilterClear_Click(object sender, RoutedEventArgs e)
        {
            cvABPOS.CustomFilter = null;
        }

        private void btnUpdateDel_Click(object sender, RoutedEventArgs e)
        {
            try
            { 
                if (dwPABPOS == null)
                    return;
                string pos="";
                foreach (DataRow row in SetProd.ABPOS.Rows)
                { 
                    pos=row["ABPAUFPOS"].ToString()+";";
                    if (!TOLINES.Contains(pos))
                        continue; 
                    row["ABPLIEFDAT"] = dwPABPOS["ABPLIEFDAT"];
                    row["ABPENDDAT"] = dwPABPOS["ABPLIEFDAT"];
                    row["ABPENDDATA"] = dwPABPOS["ABPLIEFDAT"];
                    row["ABPLIEFDATN"] = dwPABPOS["ABPLIEFDAT"];
                    m_Data.INTEXDBC.SaveABPOS(row);
                }
                foreach (DataRow row in SetProd.ICC_ABPOS_MAT.Rows)
                {
                    row["ABPLIEFDAT"] = dwPABPOS["ABPLIEFDAT"];
                    m_Data.INTEXDBC.UpdateICC_ABPOS_MAT(row);
                }
                foreach (DataRow row in SetProd.ABFOLGE.Rows)
                {
                    pos = row["ABFAUFPOS"].ToString() + ";";
                    if (!TOLINES.Contains(pos))
                        continue;
                    row["ABFSOLLDAT"] = dwPABPOS["ABPLIEFDAT"];
                    row["ABFSOLLDATA"] = dwPABPOS["ABPLIEFDAT"];
                    m_Data.INTEXDBC.SaveABFOLGE(row);
                }
                RefreshSetData(dwPABPOS);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            
            }
        }
        private void btnUpdateAR_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                /*ARBESTKZ N 
                 * ARWERT 12345
                 * ARZAHLB 100
                 * ARPAMABR N
                 * ARBERBAS 8
                 * ARFKNVS N
                 * ARFILLER 59                                            
                 * ARAENDBEN INTEXE  
                 * ARAENDDAT 20131220
                 * ABPWPSTA 59
                 * ABPAENDBEN INTEXE  
                 * ABPAENDDAT 20131220*/
                if (dwPABPOS == null)
                    return;
                string pos = "";
                foreach (DataRow row in SetProd.ABPR.Rows)
                {
                    pos = row["ARAUFPOS"].ToString() + ";";
                    if (!TOLINES.Contains(pos))
                        continue;
                    row["ARBESTKZ"] ="N";
                    row["ARWERT"] = dwPABPOS["ARWERT"];                    
                    row["ARZAHLB"] = 100;
                    row["ARPAMABR"] = "N";
                    row["ARBERBAS"] = "8";
                    row["ARFKNVS"] = "N";
                    row["ARAENDBEN"] =user;
                    row["ARAENDDAT"] = m_Data.date;
                    row["ARFILLER"] = "59                                            ";
                    m_Data.INTEXDBC.SaveABPR(row);
                }
                foreach (DataRow row in SetProd.ABPOS.Rows)
                {
                    pos = row["ABPAUFPOS"].ToString() + ";";
                    if (!TOLINES.Contains(pos))
                        continue;
                    row["ABPWPSTA"] = "59";
                    row["ABPAENDBEN"] = user;
                    row["ABPAENDDAT"] = m_Data.date;
                    m_Data.INTEXDBC.SaveABPOS(row);                  
                }
                foreach (DataRow row in SetProd.ICC_ABPOS_MAT.Rows)
                {
                    row["ARWERT"] = dwPABPOS["ARWERT"];
                    m_Data.INTEXDBC.UpdateICC_ABPOS_MAT(row);
                }
                RefreshSetData(dwPABPOS);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
             
            }
        }
        private void btnUpdateEX_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (dwPABPOS == null)
                    return;
                if (dwLIEFDAT == null)
                    return;

                string liefnr = dwLIEFDAT["LSLIEFNR"].ToString();
                string LSLIEFNA = dwLIEFDAT["LSLIEFNA"].ToString();
                string ks = Helper.Left(dwLIEFDAT["LSLIEFNA"].ToString(), 2);
                DataRow dwKS05;
                bool IsFound = false;
                dwKS05 = SetData.KSTAGZUO.NewRow();
                dwKS05["KSZMANDANT"] = "00";
                dwKS05["KSZLIEFNR"] = dwLIEFDAT["LSLIEFNR"].ToString();
                DataSet SResult = m_Data.INTEXDBC.QueryKSTAGZUO(dwKS05, 1);
                if (SResult.Tables.Count > 0)
                {
                    foreach (DataRow row in SResult.Tables[0].Rows)
                    {
                        dwKS05 = row;
                        IsFound = true;
                    }
                }
                string pos = "";
                foreach (DataRow row in SetProd.ABPOS.Rows)
                {
                    pos = row["ABPAUFPOS"].ToString() + ";";
                    if (!TOLINES.Contains(pos))
                        continue;
                    row["ABPLIEFNR"] =liefnr;
                    row["ABPANRKR"] = ks;
                  
                    if (IsFound)
                    {
                        row["ABPZLO"] = dwKS05["KSZLO"];
                        row["ABPZLB"] = dwKS05["KSZLB"];
                    }
                    else
                    {
                        row["ABPZLO"] = "01";
                        row["ABPZLB"] = "  ";
                    }
                    m_Data.INTEXDBC.SaveABPOS(row);
                }

                foreach (DataRow row in SetProd.ABFOLGE.Rows)
                {
                    pos = row["ABFAUFPOS"].ToString() + ";";
                    if (!TOLINES.Contains(pos))
                        continue; 
                    row["ABFLIEFNR"] = liefnr;
                    row["ABFALFDNR"] = "000001";
                    row["ABFBLFDNR"] = "0001";
                    row["ABFBNRKRS"] = ks;
                    row["ABFANRKRS"] = ks;
                    row["ABFKSTKRS"] = ks; 
                    row["ABFSAFOLGE"] =  row["ABFAFOLGE"]; 
                    if (IsFound)
                    {
                        row["ABFLO"] = dwKS05["KSZLO"];
                        row["ABFLB"] = dwKS05["KSZLB"];
                        row["ABFLP"] = dwKS05["KSZLP"];
                    }
                    else
                    {
                        row["ABFLO"] = "01";
                        row["ABFLB"] = "  ";
                        row["ABFLP"] = "        ";
                    }                   
                    m_Data.INTEXDBC.SaveABFOLGE(row);
                }
                foreach (DataRow row in SetProd.ICC_ABPOS_MAT.Rows)
                {
                    row["ABPLIEFNR"] = liefnr;
                    row["ABPANRKR"] = ks;
                    row["EXTFTYNAME"] =gb2312.ConvertBack(dwLIEFDAT["LSNAME1"].ToString(),null,null,null);
                    m_Data.INTEXDBC.UpdateICC_ABPOS_MAT(row);                   
                }
                RefreshSetData(dwPABPOS);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
              
            }
        }
        private void cbSECTION_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ComboBox cb = sender as ComboBox;
            txtSection.Text += cb.SelectedValue + ";";
        }

        private void TbPCDQTY_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
        {

        }
         
        
    }
}
